package com.test.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * aop 请求 返回参数获取
 * Created by apple on 2017/5/12.
 */
@Aspect
@Component
public class httpAspect {
    //    @Before("execution(public * com.test.controller.MyShowController.list(..))")
//    @Before("execution(public * com.test.controller.*.*(..))")
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(public * com.test.controller.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void logBefore(JoinPoint joinPoint) {
        logger.info("11111111111111111111");
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // url
        logger.info("url = {}", request.getRequestURL());
        // method
        logger.info("method = {}", request.getMethod());
        // client ip
        logger.info("ip = {}", request.getRemoteAddr());
        // class method
        logger.info("class_method = {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        // var
        logger.info("args = {}", joinPoint.getArgs());
    }

    @After("log()")
    public void logAfter() {
        logger.info("22222222222222222222");
    }

    @AfterReturning(pointcut = "log()", returning = "obj")
    public void logReturn(Object obj) {
        logger.info("response = {}", obj);
    }
}
